using System;
using System.Collections.Generic;
using CMS_Admin.Backend.Api.Entity;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using CMS_Admin.Backend.Api.ParamModel;
using Newtonsoft.Json;
using CMS_Admin.Backend.Api.Repository;
using CMS_Admin.Backend.Api.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;
using CMS_Admin.Backend.Api.Filters;

namespace CMS_Admin.Backend.Controllers
{
    /// <summary>
    /// 用户管理
    /// </summary>


    [Authorize]
    [Authonization]
    [ApiController]
    [Route("user")]
    public class UsersController : ControllerBase
    {
        private IRepository<Users> _usersRespository;
        private IRepository<Roles> _userRoles;
        private TokenParameter _tokenParameter;
        private readonly IConfiguration _configuration;

        public UsersController(IConfiguration configuration, IRepository<Users> usersRespository, IRepository<Roles> userRoles)
        {
            _configuration = configuration;
            _usersRespository = usersRespository;
            _userRoles = userRoles;
            _tokenParameter = _configuration.GetSection("TokenParameter").Get<TokenParameter>();
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="pager"></param>
        /// <returns></returns>
        [HttpGet]
        public dynamic Get([FromQuery] Pager pager)
        {//get请求默认从uri从获取参数，所以此处应该加上FromQuery的特性才能正确获得参数
            var pageIndex = pager.PageIndex;
            var pageSize = pager.PageSize;





            // 获得所有满足条件的记录
            // var users = _usersRespository.Table.Where(x => x.IsDeleted == false);

            var users = from user in _usersRespository.Table
                        join roles in _userRoles.Table on user.RolesId equals roles.Id
                        orderby user.Id
                        select new
                        {
                            Id = user.Id,
                            Username = user.Username,
                            Password = user.Password,
                            Nickname = user.Nickname,
                            RoleName = roles.RoleName,
                            IsActived = user.IsActived,
                            IsDeleted = user.IsDeleted,
                            CreatedTime = user.CreatedTime,
                            Remarks = user.Remarks,
                            Txcolor = user.Txcolor,
                            Bgcolor =user.Bgcolor

                        };

            if (!string.IsNullOrEmpty(pager.KeyWord))
            {
                users = users.Where(u => u.Username.Contains(pager.KeyWord) || u.Nickname.Contains(pager.KeyWord));
            }




            // 对获得的记录分页
            var u = users.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            // 返回的数据里，带有数据和分页信息
            var res = new
            {
                Code = 1000,
                Data = new { Data = u, Pager = new { pageIndex, pageSize, rowsTotal = users.Count() } },
                Msg = "获取用户列表成功^_^"
            };
            return res;
        }

        /// <summary>
        /// 根据指定id查找数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public dynamic Get(int id)
        {
            var user = _usersRespository.GetById(id);

            if (user == null)
            {
                return new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "指定用户不存在"
                };

            }
            return new
            {
                Code = 200,
                Data = user,
                Msg = "获取用户列表成功^_^"
            };

        }
        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public string Post(NewUser model)
        {

            var nickname = model.Nickname.Trim();
            var username = model.Username.Trim();
            var name = model.RoleName;
            var rolesid = _userRoles.Table.Where(r => r.RoleName == name).FirstOrDefault()?.Id;
            var u = _usersRespository.Table.Where(u => u.Username == username).FirstOrDefault();
            var password = model.Password.Trim();
            var txcolor = model.Txcolor.Trim();
            var bgcolor = model.Bgcolor.Trim();
            // var rolesid = model.RolesId;
            if (u != null)
            {

                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "用户名已存在"
                };
                return JsonHelper.Serialize(tmp);
            }

            if (string.IsNullOrEmpty(username))
            {
                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "用户名不能为空，请确认后重试"
                };
                return JsonHelper.Serialize(tmp);
            }
            var us = _userRoles.Table.Where(r => r.Id == rolesid).FirstOrDefault();

            var user = new Users
            {
                Username = username,
                Password = password,
                Nickname = nickname,
                User = _userRoles.Table.Single(r => r.Id == rolesid),
                Txcolor =txcolor,
                Bgcolor =bgcolor


            };

            _usersRespository.Insert(user);


            var res = new
            {
                Code = 200,
                Data = new
                {
                    User = user,
                    RoleName = model.RoleName
                },
                Msg = "创建用户成功"
            };
            return JsonHelper.Serialize(res);
        }


        /// <summary>
        /// 修改和伪删除指定用户
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public dynamic Put(int id, NewUser model)
        {
            var user = _usersRespository.GetById(id);
            var roles = _userRoles.GetById(id);
            var roleName = model.RoleName;
            var ur = _userRoles.Table.Where(r => r.RoleName == roleName).FirstOrDefault()?.Id;

            if (user != null)
            {
                user.Nickname = model.Nickname;
                user.Username = model.Username;
                user.Password = model.Password;
                user.RolesId = (int)ur;
                user.IsActived = model.IsActived;
                user.IsDeleted = model.IsDeleted;
                user.Remarks = model.Remarks;


                user.UpdatedTime = DateTime.Now;
                _usersRespository.Update(user);
                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = user,
                    Msg = string.Format("你修改或删除的用户的id为：{0}，已经修改成功，请注意查收", id)
                });
            }
            else
            {
                return JsonHelper.Serialize(new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "指定Id的用户不存在，请确认后重试"
                });
            }
        }

        /// <summary>
        /// 真删除指定用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {
            var user = _usersRespository.GetById(id);
            if (user != null)
            {
                _usersRespository.Delete(id);
                return new
                {
                    Code = 200,
                    Msg = string.Format("删除指定id为{0}的用户成功", id)
                };
            }
            else
            {
                return new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "指定Id的用户不存在，请确认后重试"
                };
            }

        }

        /// <summary>
        /// 登入验证
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
       
        [AllowAnonymous]
        [HttpPost, Route("token")]
        public dynamic GetToken(NewLogin model)
        {
            var username = model.Username.Trim();
            var password = model.Password.Trim();
            // var userid = model.Id;

            var user = _usersRespository.Table.Where(x => x.Username == username && x.Password == password).FirstOrDefault();

            if (user == null)
            {
                return new
                {
                    Code = 1004,
                    Data = user,
                    Msg = "用户名或密码不正确，请核对后重试"
                };
            }

            var token = TokenHelper.GenerateToekn(_tokenParameter, user);
            var refreshToken = "123456";

            var res = new
            {
                Code = 200,
                Data = new { Token = token, RefreshToken = refreshToken },
                Msg = "用户登录成功，获取token成功"
            };
            return res;
        }


        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost, Route("register")]
        public string PostRgister(NewRegister model)
        {
            var username = model.Username.Trim();
            var password = model.Password.Trim();
            var confirmPassword = model.ConfirmPassword.Trim();
            var txcolor = model.Bgcolor ?? "white";
            var bgcolor = model.Bgcolor ?? "orange";

            var u = _usersRespository.Table.Where(u => u.Username == username).FirstOrDefault();

            if (username == null && password == null && confirmPassword == null)
            {

                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "请填充所有框"
                };
                return JsonHelper.Serialize(tmp);
            }
            else if (password != confirmPassword)
            {

                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "两次填充的密码不一致"
                };
                return JsonHelper.Serialize(tmp);

            }
            else
            {


                if (u == null)
                {

                    var user = new Users
                    {
                        Username = username,
                        Password = password,
                        User = _userRoles.Table.Single(r => r.Id == 1),
                        Txcolor = model.Txcolor,
                        Bgcolor = model.Bgcolor
                    };

                    _usersRespository.Insert(user);


                    var res = new
                    {
                        Code = 200,
                        Data = user,
                        Msg = "注册成功"
                    };
                    return JsonHelper.Serialize(res);

                }
                else
                {

                    var res = new
                    {
                        Code = 650,
                        Data = "",
                        Msg = "当前用户已存在！"
                    };
                    return JsonHelper.Serialize(res);
                }
            }


        }



    }
}
